package com.xincheng.shuimalong.activity.mydetail;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.IdCardCameraActivity;
import com.xincheng.shuimalong.activity.SucceedActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.util.UnitUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 许浩 on 2017/6/18.
 */

public class ReanNameAuthenticationActivity extends BaseActivity {
    @BindView(R.id.identity_front)
    FrameLayout identityFront;
    @BindView(R.id.identity_front_tv)
    TextView identityFrontTv;
    @BindView(R.id.img_identity_front)
    ImageView imgIdentityFront;
    @BindView(R.id.img_identity_front_clear)
    ImageView imgIdentityFrontClear;
    @BindView(R.id.identity_contrary)
    FrameLayout identityContrary;
    @BindView(R.id.identity_contrary_tv)
    TextView identityContraryTv;
    @BindView(R.id.img_identity_contrary)
    ImageView imgIdentityContrary;
    @BindView(R.id.img_identity_contrary_clear)
    ImageView imgIndentityContraryClear;
    @BindView(R.id.edt_real_name)
    EditText edtRealName;
    @BindView(R.id.edt_id_card)
    EditText edtIdCard;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    private Bitmap front_id_card, contrary_id_card;

    private AlertView mPhotoAlert;
    private int mPhotoStatus;


    @Override
    public int getLayoutResId() {
        return R.layout.realname_authentication_layout;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.reanname_cert));
    }

    @Override
    public void addListener() {

    }

    private void initAlertView() {
        mPhotoAlert = new AlertView(this, null, null, getString(R.string.cancel), null, Constant.CAMERA_OR_LOCAL,
                AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0:
                        photoCamera();
                        break;
                    case 1:
                        photoLocal();
                        break;
                }
            }
        });
    }

    private void photoCamera() {
        switch (mPhotoStatus) {
            case 1://身份证正面
                Bundle bundle1 = new Bundle();
                bundle1.putInt(IntentKey.FROM, 1);
                ShowActivity.showActivityForResult(ReanNameAuthenticationActivity.this, IdCardCameraActivity.class,
                        bundle1, RequestCodeKey.INDENTIFY_FRONT);
                break;
            case 2:
                //身份证反面
                Bundle bundle2 = new Bundle();
                bundle2.putInt(IntentKey.FROM, 1);
                ShowActivity.showActivityForResult(ReanNameAuthenticationActivity.this, IdCardCameraActivity.class,
                        bundle2, RequestCodeKey.INDENTIFY_CONTRARY);
                break;
        }
    }

    private void photoLocal() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择一张图片"),
                    RequestCodeKey.TAKE_PHOTO_LOCAL);
        } catch (Exception e) {
            CommonUtil.showToast(this, "请安装文件管理器");
        }
    }

    @OnClick({R.id.identity_front, R.id.identity_contrary, R.id.btn_commit, R.id.img_identity_front_clear,
            R.id.img_identity_contrary_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.identity_front:
                if (front_id_card == null || front_id_card.isRecycled()) {
                    mPhotoStatus = 1;
                    initAlertView();
                    if (mPhotoAlert != null) {
                        mPhotoAlert.show();
                    }
                }
                break;
            case R.id.identity_contrary:
                if (contrary_id_card == null || contrary_id_card.isRecycled()) {
                    mPhotoStatus = 2;
                    initAlertView();
                    if (mPhotoAlert != null) {
                        mPhotoAlert.show();
                    }
                }
                break;
            case R.id.btn_commit:
                commit();
                break;
            case R.id.img_identity_front_clear:
                identityFrontTv.setVisibility(View.VISIBLE);
                imgIdentityFront.setVisibility(View.GONE);
                imgIdentityFrontClear.setVisibility(View.GONE);
                front_id_card.recycle();
                front_id_card = null;
                break;
            case R.id.img_identity_contrary_clear:
                identityContraryTv.setVisibility(View.VISIBLE);
                imgIdentityContrary.setVisibility(View.GONE);
                imgIndentityContraryClear.setVisibility(View.GONE);
                contrary_id_card.recycle();
                contrary_id_card = null;
                break;
        }
    }

    private void commit() {
        String realName, idCardNo;
        if (!CommonUtil.isEmpty(edtRealName)) {
            realName = getEditString(edtRealName);
        } else {
            showToast("请输入真实姓名", Toast.LENGTH_SHORT);
            return;
        }
        if (!CommonUtil.isEmpty(edtIdCard)) {
            idCardNo = getEditString(edtIdCard);
            if (!MyUtil.checkIdCard(idCardNo)) {
                showToast("身份证格式不合法");
                return;
            }
        } else {
            showToast("请输入身份证号码", Toast.LENGTH_SHORT);
            return;
        }
        if (front_id_card == null) {
            showToast("请拍摄身份证正面照片", Toast.LENGTH_SHORT);
            return;
        }
        if (contrary_id_card == null) {
            showToast("请拍摄身份证反面照片", Toast.LENGTH_SHORT);
            return;
        }
        String idCard = BitmapUtil.bitmapToBase64(front_id_card);
        String idCard_V = BitmapUtil.bitmapToBase64(contrary_id_card);
        RetroSubscrube.getInstance().postSubscrube(AppUrl.REALCERT, PostParam.realcert(PrefUtil.getString(this,
                PrefKey.TOKEN, ""), realName, idCardNo, idCard, idCard_V),
                new BaseObserver(getContext(), getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast(msg, Toast.LENGTH_SHORT);
                        Bundle extras = new Bundle();
                        PrefUtil.putBoolean(getContext(), PrefKey.LOGIN_CERT, true);
                        extras.putString(IntentKey.TITLE_MESSAGE, getString(R.string.authentication_success));
                        extras.putString(IntentKey.SUCCESS_MESSAGE, getString(R.string.authentication_success_msg));
                        ShowActivity.showActivity(getContext(), SucceedActivity.class, extras);
                        finish();
                    }
                });
    }

    private void showFrontImg() {
        identityFrontTv.setVisibility(View.GONE);
        imgIdentityFront.setVisibility(View.VISIBLE);
        imgIdentityFrontClear.setVisibility(View.VISIBLE);
        imgIdentityFront.setImageBitmap(front_id_card);
    }

    private void showContraryImg() {
        identityContraryTv.setVisibility(View.GONE);
        imgIdentityContrary.setVisibility(View.VISIBLE);
        imgIndentityContraryClear.setVisibility(View.VISIBLE);
        imgIdentityContrary.setImageBitmap(contrary_id_card);
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case Constant.CAMERA_SUCESS:
                switch (requestCode) {
                    case RequestCodeKey.INDENTIFY_FRONT:
                        //身份证正面
                        if (data != null && data.getData() != null) {
                            front_id_card = UnitUtils.getDiskBitmap(data.getData());
                            showFrontImg();
                        }
                        break;
                    case RequestCodeKey.INDENTIFY_CONTRARY:
                        //身份证反面
                        if (data != null && data.getData() != null) {
                            contrary_id_card = UnitUtils.getDiskBitmap(data.getData());
                            showContraryImg();
                        }
                        break;
                }
                break;
            case RESULT_OK:
                switch (requestCode) {
                    case RequestCodeKey.TAKE_PHOTO_LOCAL:
                        if (data != null && data.getData() != null) {
                            Uri uri = data.getData();
                            String path = CommonUtil.getLocalImagePath(this, uri);
                            Glide.with(this).asBitmap().load(path).into(new MySimpleTarget());
                        }
                        break;
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class MySimpleTarget extends SimpleTarget<Bitmap> {

        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            switch (mPhotoStatus) {
                case 1:
                    front_id_card = resource;
                    if (resource != null &&
                            resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                        front_id_card = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                    }
                    showFrontImg();
                    break;
                case 2:
                    contrary_id_card = resource;
                    if (resource != null &&
                            resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                        contrary_id_card = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                    }
                    showContraryImg();
                    break;
            }
        }
    }
}
